package Threelayer.Utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

/**
 * @author lishunlin110
 * @version 1.0
 * @description: jdbc工具类
 * @date 2021/8/23 12:21
 */
public class DbUtils {

    private static final Properties PROPERTIES=new Properties();
    private static final ThreadLocal<Connection>THREAD_LOCAL=new ThreadLocal<>();

    static {
        InputStream is=DbUtils.class.getResourceAsStream("/jdbc.properties");
        try {
            PROPERTIES.load(is);
            Class.forName(PROPERTIES.getProperty("driver"));
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

    public static Connection getConnection(){
        String url=PROPERTIES.getProperty("url");
        String passwd=PROPERTIES.getProperty("password");
        String user=PROPERTIES.getProperty("user");
        Connection con;
        con=THREAD_LOCAL.get();
        try {
            if(con==null){
                con=DriverManager.getConnection(url,user,passwd);
                THREAD_LOCAL.set(con);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return con;
    }

    //事物开始
    public static void begin(){
        Connection con;
        try {
            con=getConnection();
            con.setAutoCommit(false);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //提交事务
    public static void commit(){
        Connection con;
        try {
            con=getConnection();
            con.commit();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //回滚事务
    public static void rollback(){
        Connection con;
        try {
            con=getConnection();
            con.rollback();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    //关闭资源
    public static void closeAll(Connection con, Statement st, ResultSet rs){
        try {
            if(rs!=null){
                rs.close();
            }
            if(st!=null){
                st.close();
            }
            if(con!=null){
                con.close();
                THREAD_LOCAL.remove();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
